import { overallOptions } from "@/api/public"
import cache from "@/plugins/cache"
import { difference, assign, uniq, reject } from "lodash"

const enumCacheName = "oms_enums"

let timer
let nameGroup = []
let taskFn = []

/**
 * 获取字典
 * @param name 字典下拉
 * @param callBack 任务回调
 */
const getEnum = (name, callBack) => {
  return new Promise(async (resolve, reject) => {
    try {
      if (Array.isArray(name)) {
        nameGroup = [...nameGroup, ...name]
      } else {
        nameGroup.push(name)
      }
      // 将任务挂起。
      if (callBack) taskFn.push(callBack)
      timer && clearTimeout(timer)
      timer = setTimeout(async () => {
        if (!nameGroup.length) resolve({})
        nameGroup = uniq(nameGroup)
        let resEnum = cache.session.getJSON(enumCacheName) || {}
        for (const item of nameGroup) {
          const cacheEnums = getEnumForCache(item)
          if (cacheEnums && cacheEnums.length) resEnum[item] = cacheEnums
        }
        const differenceKeys = difference(nameGroup, Object.keys(resEnum))
        if (differenceKeys.length > 0) {
          const res = await overallOptions({
            option: "new",
            params: differenceKeys,
          })
          if (res.status === 200) {
            const originEnums = res.data
            resEnum = assign(resEnum, originEnums)
            const tryDiff = difference(nameGroup, Object.keys(resEnum))
            tryDiff.forEach((v) => {
              resEnum[v] = []
            })
          }
        }
        taskFn.forEach((item) => item(resEnum))
        cache.session.setJSON(enumCacheName, resEnum)
        timer = null
        nameGroup.length = 0
        taskFn.length = 0
        resolve(resEnum)
      }, 200)
    } catch (e) {
      reject(e)
    }
  })
}

const getEnumForCache = (name) => {
  const enums = cache.session.getJSON(enumCacheName)
  if (enums) return enums[name]
  return null
}

// 平台
import { getPlatformOptions, getCountryOption } from "@/api/public"
const getPlatformOpt = async () => {
  let resEnum = cache.session.getJSON(enumCacheName) || {}
  if (!resEnum["platform"]) {
    let { data } = await getPlatformOptions()
    data = data.map((v) => ({ label: v.platform_name, value: v.platform_id }))
    resEnum["platform"] = data
  }
  cache.session.setJSON(enumCacheName, resEnum)
  return resEnum["platform"]
}

// 站点
const getCountryOpt = async () => {
  let resEnum = cache.session.getJSON(enumCacheName) || {}
  if (!resEnum["country"]) {
    let { data } = await getCountryOption()
    data = data.map((v) => ({ label: `${v.name} ${v.country}`, value: v.id }))
    resEnum["country"] = data
  }
  cache.session.setJSON(enumCacheName, resEnum)
  return resEnum["country"]
}

const optionApiConfig = {
  platform: getPlatformOpt,
  country: getCountryOpt,
}

const getAloneEnum = async (keys) => {
  let resEnum = cache.session.getJSON(enumCacheName) || {}
  let res = {}
  for (let i = 0; i < keys.length; i++) {
    let key = keys[i]
    if (!resEnum[key]) {
      console.log(optionApiConfig)
      resEnum[key] = await optionApiConfig?.[key]()
    }
    res[key] = resEnum[key]
  }
  cache.session.setJSON(enumCacheName, resEnum)
  return res
}

export { getEnum, getAloneEnum }
